/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { message } from 'antd';
import { getOperatorList, saveOperator, editorOperator, zySaveOperator } from '@/services/api';
import {
  deliveryStatus,
  allowanceCount,
  modifyCount,
  quickStatus,
  batchDelete,
  transferOperator,
  reapply,
} from '@/services/operator';

const noop = () => {};
export default {
  namespace: 'operator',

  state: {
    wxCourierData: null,
    qrCodeData: null,
    wxList: null,
    list: null,
    pagination: null,
    company_site_id: null, // 搜索后需要选中的站点id
    expandedRowKeys: ['yd', 'yt', 'ems'], // 需要配置展开项的品牌
    hasSearch: false, // 是否搜索过业务员
  },

  effects: {
    *getOperatorList({ payload = {}, then = noop }, { call, put, select }) {
      const { currentStation = {} } = yield select(_ => _.station);
      const { site_id } = currentStation;
      const hasSearch = !!payload.keyWords;
      const params = {
        ...payload,
        site_id,
      };
      // 判断，当通过搜索获取业务员时，需要删除site_id
      hasSearch && delete params.site_id;

      const response = yield call(getOperatorList, { ...params });
      if (!response) return;
      const { code, data = {} } = response;
      const { result = [], total, page, size } = data || {};

      if (code == 0 && data && result.length > 0) {
        yield put({
          type: 'updateState',
          payload: {
            list: result,
            pagination: {
              total,
              pageSize: size,
              current: page,
            },
            company_site_id: result[0].company_site_id,
            hasSearch,
          },
        });
        then(data);
      } else {
        yield put({
          type: 'updateState',
          payload: {
            list: [],
            pagination: {
              total,
              pageSize: size,
              current: page,
            },
          },
          hasSearch,
        });
      }
    },
    *saveOperator({ payload, then }, { call, put, select }) {
      const { id, isZyAccount } = payload;
      const request = id ? editorOperator : isZyAccount ? zySaveOperator : saveOperator;
      delete payload.isZyAccount;
      const response = yield call(request, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        if (id) {
          // 编辑
          const { list } = yield select(_ => _.operator);
          for (let i = 0, len = list.length; i < len; i++) {
            const currentOperator = list[i];
            if (currentOperator.id == id) {
              list[i] = {
                ...currentOperator,
                ...payload,
              };
              break;
            }
          }
          yield put({
            type: 'updateState',
            payload: {
              list,
            },
          });
        } else {
          // 更新
          const { site_code } = payload;
          yield put({
            type: 'getOperatorList',
            payload: {
              site_code,
            },
          });
        }
        message.success('保存成功');
        then(response);
      } else if (code == 1060) {
        then(response);
      } else {
        message.error(msg);
      }
    },
    *deleteOperator({ payload, then = noop }, { call, put }) {
      const response = yield call(batchDelete, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        yield put({ type: 'getOperatorList' });
        then();
        message.success('已删除');
      } else {
        message.error(msg);
      }
    },
    *deliveryStatus({ payload, then }, { call }) {
      const response = yield call(deliveryStatus, payload);
      if (!response) return;
      // 开通、关闭时处理
      const { type } = payload;
      const { code } = response;
      if (code == 0) {
        message.success(type == 0 ? '已关闭' : '已开通');
      }
      then && then(response);
    },
    *allowanceCount({ payload, then }, { call, select, put }) {
      const { courier_no, radioValue, count } = payload;
      const num =
        payload.select == 'increase' ? count : payload.select == 'reduce' ? `-${count}` : count;
      const response = yield call(radioValue == 1 ? allowanceCount : modifyCount, {
        courier_no,
        num,
      });
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        if (courier_no) {
          // 修改限额
          const { list } = yield select(_ => _.operator);

          for (let i = 0, len = list.length; i < len; i++) {
            const currentOperator = list[i];
            if (currentOperator.courier_no == courier_no) {
              if (payload.select == 'increase') {
                list[i] = {
                  ...currentOperator,
                  num: parseInt(currentOperator.num) + parseInt(payload.count),
                };
              } else if (payload.select == 'reduce') {
                list[i] = {
                  ...currentOperator,
                  num: parseInt(currentOperator.num) - parseInt(payload.count),
                };
              } else {
                list[i] = {
                  ...currentOperator,
                  num: payload.count,
                };
              }
              break;
            }
          }
          yield put({
            type: 'updateState',
            payload: {
              list,
            },
          });
        }
        message.success('修改成功');
        then(code);
      } else {
        message.error(msg);
      }
    },
    *quickStatus({ payload, then }, { call, select, put }) {
      const response = yield call(quickStatus, payload);
      // if (!response) return;
      // 开通、关闭时处理
      const { courier_no, type } = payload;
      const { code } = response;
      if (code == 0) {
        const { list } = yield select(_ => _.operator);
        yield put({
          type: 'updateState',
          payload: {
            list: list.map(item => {
              if (item.courier_no === courier_no) {
                if (type == '1') {
                  item.switch = payload.switch;
                } else if (type == '3') {
                  item.barSwitch = payload.switch;
                }
              }
              return item;
            }),
          },
        });
        message.success(payload.switch == 0 ? '已关闭' : '已开通');
      }
      then && then(response);
    },
    *batchDelete({ payload, then = noop }, { call, put }) {
      const response = yield call(batchDelete, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        yield put({ type: 'getOperatorList' });
        then();
        message.success('已删除');
      } else {
        message.error(msg);
      }
    },
    *transferOperator({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(transferOperator, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success(msg);
        __dva_resolve(response);
      } else {
        message.error(msg);
        __dva_reject(response);
      }
    },
    *reapply({ payload, then = noop }, { call }) {
      const response = yield call(reapply, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        then();
        message.success(msg);
      } else {
        message.error(msg);
      }
    },
  },

  reducers: {
    updateState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
